package cool.xiaokang.familyaccount.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.serializer.PropertyFilter;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cool.xiaokang.familyaccount.dao.TopicDao;
import cool.xiaokang.familyaccount.pojo.Reply;
import cool.xiaokang.familyaccount.pojo.Topic;
import cool.xiaokang.familyaccount.pojo.User;
import cool.xiaokang.familyaccount.service.RegionService;
import cool.xiaokang.familyaccount.service.ReplyService;
import cool.xiaokang.familyaccount.service.TopicService;
import cool.xiaokang.familyaccount.utils.DateFormateUtil;
import cool.xiaokang.familyaccount.utils.PageBean;
import cool.xiaokang.familyaccount.utils.ResponseUtils;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Controller
@Scope("prototype")
public class TopicAction extends ActionSupport implements ModelDriven<Topic> {
	private static final long serialVersionUID = -8353194473069274115L;
	private Topic topic = new Topic();
	private Integer region_id;
	private Integer regionId;
	private Integer page;
	private Integer rows;
	private String topic_ids;
	private Integer badcount;
	private String keyword;

	@Autowired
	private TopicService topicService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private ReplyService replyService;

	// 进入主题帖
	public String list() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		session.setAttribute("region_id", region_id);
		return "list";
	}

	// 指定交流大区的帖子（置顶、加精、帖子发布时间降序）
	public String listCurrentUser() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		regionId = (Integer) session.getAttribute("region_id");
		DetachedCriteria dc = DetachedCriteria.forClass(Topic.class);
		if (StringUtils.isNotBlank(keyword)) {
			dc.add(Restrictions.like("topic_title", "%" + keyword + "%"));
		}
		dc.add(Restrictions.eq("del", '0'));
		dc.add(Restrictions.eq("region.region_id", regionId));
		dc.addOrder(Order.desc("is_top"));
		dc.addOrder(Order.desc("is_good"));
		dc.addOrder(Order.desc("topic_datetime"));
		List<Topic> topics = topicService.findList(dc);
		PropertyFilter filter = new PropertyFilter() {
			@Override
			public boolean apply(Object object, String name, Object value) {
				boolean flag = true;
				if (name.equals("region")) {
					flag = false;
				}
				return flag;
			}
		};
		ResponseUtils.respListRef(ServletActionContext.getResponse(), topics, filter);
		return NONE;
	}

	public String showContent() {
		Topic topic1 = topicService.showContent(topic.getTopic_id());
		DetachedCriteria dc = DetachedCriteria.forClass(Reply.class);
		dc.add(Restrictions.eq("topic.topic_id", topic1.getTopic_id()));
		dc.addOrder(Order.asc("reply_datetime"));
		List<Reply> replies = replyService.findByCriteria(dc);
		ActionContext.getContext().put("topic", topic1);
		ActionContext.getContext().put("replylist", replies);
		return "show";
	}

	public String add() {
		User user = (User) ActionContext.getContext().getSession().get("currentUser");
		topic.setUser(user);
		topicService.save(topic);
		return "tolist";
	}

	// 进入我的帖子jsp
	public String myList() throws Exception {
		User user = (User) ActionContext.getContext().getSession().get("currentUser");
		List<Reply> xiaoxi = replyService.findByTopicAndUser(user.getUser_id());
		List<Reply> replys = replyService.findByCriteria(user.getUser_id());
		ActionContext.getContext().put("replys", replys);
		ActionContext.getContext().put("xiaoxi", xiaoxi);
		return "mylist";
	}

	// 通过当前用户查找主题帖
	public String findByUser() {
		User user = (User) ActionContext.getContext().getSession().get("currentUser");
		DetachedCriteria dc = DetachedCriteria.forClass(Topic.class);
		dc.add(Restrictions.eq("del", '0'));
		dc.add(Restrictions.eq("user.user_id", user.getUser_id()));
		dc.addOrder(Order.desc("is_top"));
		dc.addOrder(Order.desc("is_good"));
		dc.addOrder(Order.desc("topic_datetime"));
		List<Topic> topics = topicService.findList(dc);
		PropertyFilter filter = new PropertyFilter() {
			@Override
			public boolean apply(Object object, String name, Object value) {
				boolean flag = true;
				if (name.equals("user")) {
					flag = false;
				} else if (name.equals("region")) {
					flag = false;
				}
				return flag;
			}
		};
		ResponseUtils.respList(ServletActionContext.getResponse(), topics, filter);
		return NONE;
	}

	// 删除主题帖
	public String deleteById() throws IOException {
		String flag = "1";
		try {
			topicService.deleteById(topic.getTopic_id());
		} catch (Exception e) {
			flag = "0";
		}
		ServletActionContext.getResponse().getWriter().write(flag);
		return NONE;
	}

	// 通过ID查找主题帖
	public String findById() {
		Topic t = topicService.findById(topic.getTopic_id());
		ActionContext.getContext().put("topic", t);
		return "toedit";
	}

	// 修改主题帖
	public String update() {
		topicService.update(topic);
		return "toshow";
	}

	// 结贴
	public String end() throws IOException {
		String flag = "1";
		try {
			topicService.end(topic.getTopic_id());
		} catch (Exception e) {
			flag = "0";
			e.printStackTrace();
		}
		ServletActionContext.getResponse().getWriter().write(flag);
		return NONE;
	}

	// 点赞
	public String zan() throws IOException {
		String flag = "1";
		try {
			topicService.zan(topic.getTopic_id());
		} catch (Exception e) {
			flag = "0";
		}
		ServletActionContext.getResponse().getWriter().write(flag);
		return NONE;
	}

	// 鄙视
	public String bad() throws IOException {
		String flag = "1";
		try {
			topicService.bad(topic.getTopic_id());
		} catch (Exception e) {
			flag = "0";
		}
		ServletActionContext.getResponse().getWriter().write(flag);
		return NONE;

	}

	// 管理员查看主题帖
	@RequiresPermissions("topic-list")
	public String pageQuery() throws IOException {
		PageBean pb = new PageBean();
		DetachedCriteria dc = DetachedCriteria.forClass(Topic.class);
		if (StringUtils.isNotBlank(topic.getTopic_title())) {
			dc.add(Restrictions.like("topic_title", "%" + topic.getTopic_title() + "%"));
		}
		if (topic.getIs_top() != null && !"".equals(topic.getIs_top())) {
			dc.add(Restrictions.eq("is_top", topic.getIs_top()));
		}
		if (topic.getIs_good() != null && !"".equals(topic.getIs_good())) {
			dc.add(Restrictions.eq("is_good", topic.getIs_top()));
		}
		if (topic.getIs_end() != null && !"".equals(topic.getIs_end())) {
			dc.add(Restrictions.eq("is_end", topic.getIs_end()));
		}
		if (topic.getDel() != null && !"".equals(topic.getDel())) {
			dc.add(Restrictions.eq("del", topic.getDel()));
		}
		if (topic.getTopic_datetime() != null) {
			// 将日期向后推移一天
			Calendar ca = Calendar.getInstance();
			ca.setTime(topic.getTopic_datetime());
			ca.add(Calendar.DATE, 1);
			Date date = ca.getTime();
			dc.add(Restrictions.between("topic_datetime", DateFormateUtil.transfer(topic.getTopic_datetime()), date));
		}
		if (badcount != null && badcount == 10) {
			dc.add(Restrictions.ge("topic_bad", 20));
		}
		pb.setDetachedCriteria(dc);
		pb.setCurrentPage(page);
		pb.setPageSize(rows);
		topicService.pageQuery(pb);
		PropertyFilter filter = new PropertyFilter() {
			@Override
			public boolean apply(Object object, String name, Object value) {
				boolean flag = true;
				if (name.equals("detachedCriteria")) {
					flag = false;
				} else if (name.equals("currentPage")) {
					flag = false;
				} else if (name.equals("pageSize")) {
					flag = false;
				} else if (name.equals("age")) {
					flag = false;
				} else if (name.equals("birthday_s")) {
					flag = false;
				}
				return flag;
			}
		};
		ResponseUtils.respPageBeanRef(ServletActionContext.getResponse(), pb, filter);
		return NONE;
	}
	
	//批量删除
	public void deleteBatch(String topic_ids) {
		topicService.deleteBatch(topic_ids);
	}
	
	@RequiresPermissions("topic-top")
	public String top() {
		topicService.top(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-good")
	public String good() {
		topicService.good(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-delete")
	public String deleteBatch() {
		topicService.deleteBatch(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-notop")
	public String noTop() {
		topicService.notop(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-nogood")
	public String noGood() {
		topicService.nogood(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-undelete")
	public String noDelete() {
		topicService.nodelete(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-end")
	public String adminend() {
		topicService.adminend(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-unend")
	public String unend() {
		topicService.unend(topic_ids);
		return "adminshow";
	}

	@RequiresPermissions("topic-confirm")
	public String confirm() {
		topicService.confirm(topic.getTopic_id());
		return "adminconfirm";
	}

	@Override
	public Topic getModel() {
		return topic;
	}
}
